package cn.tedu.basic;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

//测试  反射
public class Test9 {
    public static void main(String[] args) throws Exception, IllegalAccessException {
        Class<Girl> c = Girl.class;
        Method(c);
    }
    public static void Method(Class c) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获取所有的方法
        Method[] m = c.getMethods();
        for (Method me : m){
            String name = me.getName();
            Class<?>[] pt = me.getParameterTypes();
            System.out.println(name);
            System.out.println(Arrays.toString(pt));
        }
        //获取所有的成员变量
        Field[] f = c.getFields();
        for (Field fi : f){
            String name = fi.getName();
            System.out.println(name);
            String name1 = fi.getType().getName();
            System.out.println(name1);//类型名称
        }
        //获取所有的构造方法
        Constructor[] con = c.getConstructors();
        for (Constructor cons : con){
            String name = cons.getName();
            Class[] pt = cons.getParameterTypes();
            System.out.println(name);
            System.out.println(Arrays.toString(pt));
        }
        //新建对象
        Object o = c.newInstance();//触发无参构造方法
        Constructor co = c.getConstructor();
        String name = co.getName();
        System.out.println(name);
        Constructor co1 = c.getConstructor(String.class);
        System.out.println(co1.getName());
        Object o1 = co1.newInstance("yumin");
        System.out.println(o1);
        //成员变量利用反射set/get
        Field f1 = c.getField(name);
        Object o2 = c.newInstance();
        f1.set(o2,"yangzi");
        Object o3 = f1.get(o2);
        System.out.println(o3);
        //获取一个方法，利用反射执行方法
        Method m1 = c.getMethod("make", String.class);
        Object o4 = c.newInstance();
        m1.invoke(o4,"me");
        //暴力反射执行私有方法
        Method m2 = c.getDeclaredMethod("get", int.class);
        Object o5 = c.newInstance();
        m2.setAccessible(true);
        m2.invoke(o5,20);
        //暴力反射给成员变量set/get
        Field f2 = c.getDeclaredField(name);
        Object o6 = c.newInstance();
        f2.setAccessible(true);
        f2.set(o6,"Angelababy");
        Object o7 = f2.get(o6);
        System.out.println(o7);


    }
}
